package com.auto.api.common.exception;


import com.auto.api.common.enums.ResultCode;
import com.auto.api.common.enums.ResultEnum;

/**
 * Description: 静态常量
 *
 * @author liangshf
 * @date 2019-03-04
 */
@SuppressWarnings("serial")
public class BusinessException extends RuntimeException {

    /**
     * 异常编码
     */
    private ResultEnum<String> code = ResultCode.BUSINESS_ERROR;

    private Object data;

    private Object[] args;


    public ResultEnum<String> getCode() {
        return code;
    }

    public Object getData() {
        return data;
    }

    public BusinessException(ResultEnum<String> code, String message, Throwable cause) {
        this(message, cause);
        this.code = code;
    }

    public BusinessException(ResultEnum<String> code, Throwable cause) {
        this(code, code.getDesc(), cause);
    }

    public BusinessException(ResultEnum<String> code, String message) {
        super(message);
        this.code = code;
    }


    public BusinessException(ResultEnum<String> code) {
        this(code, code.getDesc());
    }

    @Override
    public String getMessage() {
        String message = super.getMessage();
        if (args != null && args.length > 0) {
            try {
                return String.format(message, args);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return message;
    }

    public BusinessException(final String message) {
        super(message);
    }

    public BusinessException(final String message, final Throwable cause) {
        super(message, cause);
    }

    /**
     * 根据异常代码，获取错误描述信息，其中错误描述信息可以动态组装 :args[0]对应{0},以此类推
     *
     * @param code
     *            :异常代码
     * @param args
     *            :动态参数
     **/
    public BusinessException(final ResultEnum<String> code, final Object... args) {
        this.code=code;
        this.args = args;
    }

    public BusinessException(final Throwable cause) {
        super(cause.getMessage(), cause);
    }

    /**
     * 返回的data数据
     * @param data 数据
     * @return 当前异常对象
     */
    public BusinessException data(final Object data) {
        this.data = data;
        return this;
    }

    /**
     * 对于带位的信息需要添加参数
     * @param args 信息文本占位参数
     * @return 当前异常对象
     */
    public BusinessException args(final Object... args) {
        this.args = args;
        return this;
    }

}
